package com.orgname.glvone.glvtwo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.orgname.glvone.glvtwo.common.constant.CacheKeyEnum;
import com.orgname.glvone.glvtwo.common.constant.ErrorNo;
import com.orgname.glvone.glvtwo.common.exception.BusinessException;
import com.orgname.glvone.glvtwo.common.util.SHA1;
import com.orgname.glvone.glvtwo.domain.entity.User;
import com.orgname.glvone.glvtwo.domain.mapper.UserMapper;
import com.orgname.glvone.glvtwo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    RedisTemplate<String, Object> redisTemplate;

    @Value("${login.expire}")
    private Integer loginExpireTime;

    @Override
    public String login(String name, String password) {
        password = SHA1.encryption(password);
        User user = super.lambdaQuery().eq(User::getName, name).eq(User::getPassword, password).getEntity();
        if (user == null) {
            throw new BusinessException("账号/密码错误", ErrorNo.LOGIN_FAIL);
        }
        String ticket = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(CacheKeyEnum.UserInfoStringCache.key(ticket), user, loginExpireTime, TimeUnit.MINUTES);
        return ticket;
    }

    @Override
    public User validateTicket(String ticket) {
        if (Boolean.FALSE.equals(redisTemplate.hasKey(CacheKeyEnum.UserInfoStringCache.key(ticket)))) {
            throw new BusinessException("ticket non-existent", ErrorNo.UN_LOGIN);
        }

        return (User) redisTemplate.opsForValue().get(ticket);
    }

    @Override
    public String loginOther(String name) {


        return null;
    }
}
